<template>
  <scroll-view :scroll-top="scrollTopHeight" scroll-y="true" class="chatList" scroll-with-animation="true">
    <view class="main">
      <view class="box">
        <view class="left" @click="goPage(`/pages/myPage/MyBusinessCard/MyBusinessCard?cardId=${orderDetails?.userId}&pageType=other`)">
          <image :src="orderDetails?.avatar" class="headImage" mode="scaleToFill" />
          <view class="nameBox">
            <view class="name">
              <text>{{ orderDetails?.name }}</text>
              <image v-if="orderDetails?.level === '1'" src="../static/home/hg.png" mode="scaleToFill" />
              <view v-if="orderDetails?.authFlag === '1'" class="authLabel"><image src="../static/home/yrz.png" mode="scaleToFill" />已认证</view>
            </view>
            <view class="zw">{{ orderDetails?.company }} {{ orderDetails?.job }} </view>
            <view class="zw">{{ orderDetails?.createTime }}</view>
          </view>
        </view>

        <view v-if="isSelf">
          <view class="lxt" @click="changeComment">{{ orderDetails?.commentFlag === "0" ? "开启" : "关闭" }}评论</view>
          <view class="delete" @click="deleteFn">删除</view>
        </view>
        <view class="lxt" v-else @click="goPage(`/pages/myPage/MyBusinessCard/MyBusinessCard?cardId=${orderDetails?.userId}&pageType=other`)">联系他</view>
      </view>
      <view class="hyLabelList">
        行业: <view class="hyLabel" v-for="(item, index) in orderDetails?.industryList" :key="index"> {{ item.industryName }} </view>
        <view class="hyLabel">有效期： {{ orderDetails?.validDate }} </view>
      </view>
      <view class="ctn">
        {{ orderDetails?.content }}
      </view>
      <view class="imgBox">
        <image :src="item" v-for="(item, index) in orderDetails?.fileList" @click.stop="TanPreviewImage(orderDetails?.fileList, index)" :key="index" mode="scaleToFill" />
      </view>
    </view>
    <view class="main plBox">
      <view class="tabList">
        <view :class="{ item: true, active: tabActive === '1' }" @click="tabClick('1')"
          >讨论 <text>{{ orderDetails?.commentCount }}</text>
        </view>
        <!-- <view :class="{ item: true, active: tabActive === '2' }" @click="tabClick('2')">转发 <text>120</text> </view> -->
        <view :class="{ item: true, active: tabActive === '3' }"
          >点赞 <text>{{ orderDetails?.likeCount }}</text>
        </view>
      </view>
      <template v-if="commentList.length > 0">
        <view class="pjBox" v-for="(item, index) in commentList" :key="index">
          <view class="pjName">
            <image :src="item.avatar" mode="scaleToFill" class="left"></image>
            <view class="right">
              <view class="name">{{ item.nickName }}</view>
              <view class="nr">{{ item.content }}</view>
            </view>
          </view>
          <view class="pjInfo" v-if="item.subCommentList.length > 0">
            <view class="info" @click="showComments('parentId', { ...i, floorId: item.id })" v-for="(i, index) in item.subCommentList" :key="index">
              <view v-if="i.replyUserId">
                <text>{{ i.replyNickName }}</text>
                回复
                <text>@{{ i.nickName }}：</text>
              </view>
              <text v-else>{{ i.nickName }}：</text>{{ i.content }}
            </view>
            <view class="lookmore" v-if="item.subCommentCount > 5 && item.subCommentCount !== item.subCommentList.length" @click="lookMore(item)"
              >查看全部 {{ item.subCommentCount }} 条回复 <u-icon name="arrow-right" size="14" color="#1676FD"></u-icon
            ></view>
          </view>
          <view class="bottomPl">
            <view>发布于{{ item.createTime }} {{ item.city }}</view>
            <u-icon name="chat" size="24" color="#bebebe" @click="showComments('floorId', item)"></u-icon>
          </view>
        </view>
      </template>
      <view v-else style="width: 100%; display: flex; justify-content: center; margin-top: 15rpx">
        <u-empty mode="list"></u-empty>
      </view>

      <u-popup :show="show" mode="bottom" @close="close" @open="open" v-if="show">
        <view class="plInputBox">
          <view class="input" :style="{ width: plInfo ? '100%' : '80%' }">
            <u-textarea
              :height="60"
              :cursorSpacing="100"
              :focus="focus"
              border="none"
              :showConfirmBar="false"
              v-model="plInfo"
              placeholder="快发表你的评论吧"
              count
              autoHeight
              maxlength="300"
            ></u-textarea>
          </view>
          <view class="btnBox">
            <u-button type="primary" v-if="plInfo" size="small" @click="postComments">发布</u-button>
          </view>
        </view>
      </u-popup>
      <view class="buttomBox">
        <view class="iconBox">
          <view class="itemBox" @click="showComments('postId', '')">
            <image class="icon" src="../../static/home/pl.png" mode="scaleToFill" />
            <view>评论</view>
          </view>
          <view class="itemBox" @click="likeFn">
            <image v-if="orderDetails?.isLike === '1'" class="icon" src="../../static/home/dz_active.png" mode="scaleToFill" />
            <image v-else class="icon" src="../../static/home/dz.png" mode="scaleToFill" />
            <view>{{ orderDetails?.isLike === "1" ? "已点赞" : "点赞" }} </view>
          </view>
          <view class="itemBox" @click="shareFn">
            <image class="icon" src="../../static/home/fx.png" mode="scaleToFill" />
            <view>分享</view>
          </view>
        </view>
        <view class="btn" v-if="isSelf && istgStatus === '1'" @click.stop="goTop">去置顶</view>
        <view class="btn" v-if="!isSelf" @click="goPage(`/pages/myPage/MyBusinessCard/MyBusinessCard?cardId=${orderDetails?.userId}&pageType=other`)">立即联系</view>
      </view>
    </view>
  </scroll-view>
  <LimePainter v-if="orderDetails" :info="orderDetails" ref="poterCom" />
</template>

<script lang="ts" setup>
import LimePainter from "@/components/painter.vue";
import { changeCommentFlag, deletePost, getCommentListByPostId, getSubComment, getUserPostInfo, likeUserPost, postComment, unlikeUserPost } from "@/api/order";
import { onMounted, ref } from "vue";
import { goPage, TanPreviewImage } from "@/utils/commonFn";
//@ts-ignore
import { onReachBottom, onShow } from "@dcloudio/uni-app";
import dayjs from "dayjs";
import { configKey } from "@/api/my";
const { id } = defineProps<{
  id: string;
}>();
const show = ref(false);
const focus = ref(false);
const plInfo = ref("");
const poterCom = ref();
const tabActive = ref("1");
const orderDetails = ref<orderTypes.orderDetails>();
const isSelf = ref();
const commentList = ref<orderTypes.commentList[]>([]);
const currentPlType = ref();
const scrollTopHeight = ref(0);
const istgStatus = ref();
const isStatus = ref(false);
onMounted(async () => {
  if (isStatus.value) {
    uni.showLoading({
      title: "加载中",
    });
    const res1 = await configKey("promotion_switch");
    istgStatus.value = res1.data;
  }
});
onShow(async () => {
  getInfo();
});
const shareFn = () => {
  poterCom.value.save();
};
const getInfo = async () => {
  try {
    const res = await getUserPostInfo({ id });
    isStatus.value = true;
    orderDetails.value = res.data;
    isSelf.value = orderDetails.value?.userId == uni.getStorageSync("userInfo").id;
    getPostComment();
    uni.hideLoading();
  } catch (error: any) {
    console.log(error);
    if (error?.code === 561 && uni.getStorageSync("userInfo").level !== "1") {
      uni.showModal({
        title: "提示",
        cancelText: "返回",
        confirmText: "开通会员",
        content: "您未开通会员，暂时无法查看",
        success: function (res) {
          if (res.confirm) {
            goPage("/pages/myPage/activateMembership");
          }
          if (res.cancel) {
            uni.switchTab({ url: "/pages/home/home" });
          }
        },
      });
      return;
    }
    if (error.code === 561) {
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    }
  }
};
const formData = ref({
  pageNum: 1,
  pageSize: 10,
  postId: "",
});
const status = ref("loadmore");
const goTop = () => {
  if (orderDetails.value) {
    goPage(`/pages/myPage/myPosts/addPost?pageType=${orderDetails.value.type}&id=${orderDetails.value.id}`);
  }
};
const getPostComment = async () => {
  if (status.value == "nomore") {
    return;
  }
  status.value = "loadmore";
  formData.value.postId = orderDetails.value?.id + "";
  const res = await getCommentListByPostId(formData.value);
  commentList.value = commentList.value.concat(res.rows);
  if (commentList.value.length >= (res?.total as number)) {
    status.value = "nomore";
  } else {
    status.value = "loadmore";
  }
};
onReachBottom(() => {
  formData.value.pageNum++;
  getPostComment();
});
const rest = () => {
  formData.value.pageNum = 1;
  status.value = "loadmore";
  getPostComment();
};
const deleteFn = () => {
  uni.showModal({
    title: "提示",
    content: "您确定要删除吗？",
    success: async function (res) {
      if (res.confirm && orderDetails.value) {
        await deletePost({ id: orderDetails.value.id });
        uni.showToast({
          title: "删除成功",
          icon: "success",
          position: "top",
          success() {
            uni.navigateBack();
          },
        });
      }
    },
  });
};
const changeComment = () => {
  uni.showModal({
    title: "提示",
    content: `您确定要${orderDetails.value?.commentFlag === "0" ? "开启" : "关闭"}评论吗？`,
    success: async function (res) {
      if (res.confirm && orderDetails.value) {
        await changeCommentFlag({ id: orderDetails.value.id, commentFlag: orderDetails.value?.commentFlag === "0" ? "1" : "0" });
        uni.showToast({
          title: `${orderDetails.value?.commentFlag === "0" ? "开启" : "关闭"}成功`,
          icon: "success",
          position: "top",
          success() {
            getInfo();
          },
        });
      }
    },
  });
};
const showComments = (type: string, info: any) => {
  const userInfo: myTypes.userInfo = uni.getStorageSync("userInfo");
  if (!userInfo.mobile) {
    uni.showModal({
      title: "提示",
      cancelText: "否",
      confirmText: "是",
      content: "您当前未登录，是否前往登录",
      success: function (res) {
        if (res.confirm) {
          goPage("/pages/myPage/login");
        }
      },
    });
    return;
  }
  if (userInfo.cardFlag == 0) {
    uni.showModal({
      title: "提示",
      cancelText: "否",
      confirmText: "是",
      content: "您当前还没有名片，是否前往创建",
      success: function (res) {
        if (res.confirm) {
          goPage("/pages/myPage/MyBusinessCard/createBusinessCard");
        }
      },
    });
    return;
  }
  if (userInfo.authFlag == "0") {
    uni.showModal({
      title: "提示",
      cancelText: "否",
      confirmText: "是",
      content: "您当前还未实名认证，是否前往",
      success: function (res) {
        if (res.confirm) {
          goPage("/pages/myPage/businessCardAuth");
        }
      },
    });
    return;
  }
  show.value = true;
  focus.value = true;
  currentPlType.value = {
    type,
    ...info,
  };
};
const tabClick = (e: string) => {
  tabActive.value = e;
};
const open = () => {
  show.value = true;
  console.log("open");
};
const close = () => {
  show.value = false;
  console.log("close");
};
const postComments = async () => {
  let obj = { postId: orderDetails.value?.id, content: plInfo.value, floorId: "", parentId: "" };
  console.log(currentPlType.value, "currentPlType");
  let currentUserInfo = uni.getStorageSync("userInfo");
  console.log(currentUserInfo.value, "currentUserInfo");
  let arr: any = commentList.value;
  if (currentPlType.value.type === "postId") {
    let objCom = {
      commentUserId: currentUserInfo.id,
      avatar: currentUserInfo.avatar,
      content: plInfo.value,
      nickName: currentUserInfo.nickName,
      city: currentUserInfo.city,
      createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      //@ts-ignore
      id: uni.$u.random(1, 3),
      subCommentList: [],
    };
    arr.unshift(objCom);
  }
  if (currentPlType.value.type === "floorId") {
    obj.floorId = currentPlType.value.id;
    let objCom = {
      commentUserId: currentUserInfo.id,
      content: plInfo.value,
      nickName: currentUserInfo.nickName,
    };
    console.log(arr, currentPlType.value);
    arr.forEach((item: any) => {
      if (item.id === currentPlType.value.id) {
        item.subCommentCount += 1;
        item.subCommentList.push(objCom);
      }
    });
  }
  if (currentPlType.value.type === "parentId") {
    obj.parentId = currentPlType.value.id;
    obj.floorId = currentPlType.value.floorId;
    let objCom = {
      commentUserId: currentUserInfo.id,
      content: plInfo.value,
      nickName: currentPlType.value.nickName,
      replyNickName: currentUserInfo.nickName,
      replyUserId: currentPlType.value.commentUserId,
    };
    console.log(arr, currentPlType.value);
    arr.forEach((item: any) => {
      if (item.id === currentPlType.value.floorId) {
        item.subCommentCount += 1;
        item.subCommentList.push(objCom);
      }
    });
  }
  await postComment(obj);

  // console.log(commentList.value);
  commentList.value = arr;
  uni.showToast({
    title: "评论成功",
  });
  // const res = await getCommentListByPostId(formData.value);
  // commentList.value = res.rows;
  plInfo.value = "";
  show.value = false;
};
const likeFn = async () => {
  if (orderDetails.value?.isLike === "1") {
    await unlikeUserPost({ id: orderDetails.value?.id });
  } else {
    await likeUserPost({ id: orderDetails.value?.id });
  }
  getInfo();
};
const lookMore = async (item: any) => {
  const res = await getSubComment({
    postId: orderDetails.value?.id,
    floorId: item.id,
  });
  item.subCommentList = res.data;
};

const blur = () => {
  focus.value = false;
};
</script>

<style scoped lang="less">
.main {
  overflow: hidden;
  background: #fff;
  padding: 32rpx 44rpx;
}
.box {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left {
    width: calc(100% - 150rpx);
    display: flex;
    .headImage {
      width: 112rpx;
      height: 112rpx;
      margin-right: 20rpx;
      border-radius: 50%;
    }
    .nameBox {
      width: calc(100% - 120rpx);
      .name {
        display: flex;
        align-items: center;
        text {
          font-size: 32rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          color: #1e1e1e;
          line-height: 44rpx;
        }
        & > image {
          width: 28rpx;
          height: 28rpx;
          margin-left: 10rpx;
        }
      }
      .zw {
        font-size: 24rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #bebebe;
        line-height: 46rpx;
      }
    }
  }
  .lxt,
  .delete {
    text-align: center;
    background: #e7f1fe;
    border-radius: 28rpx;
    padding: 10rpx 22rpx;
    font-size: 26rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #1676fd;
    line-height: 36rpx;
    margin-bottom: 16rpx;
  }
  .delete {
    color: #fa693b;
    background: #feede7;
  }
}
.hyLabelList {
  display: flex;
  flex-wrap: wrap;
  font-size: 22rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #bebebe;
  line-height: 32rpx;
  margin-top: 22rpx;
  margin-left: 120rpx;
  margin-bottom: 30rpx;
  .hyLabel {
    background: #f8f8f8;
    padding: 0 12rpx;
    margin-right: 8rpx;
    margin-bottom: 10rpx;
  }
}
.ctn {
  font-size: 32rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #1e1e1e;
  line-height: 64rpx;
}
.plBox {
  margin-top: 20rpx;
  padding-bottom: 160rpx;
  .tabList {
    display: flex;
    align-items: center;
    .item {
      margin-right: 48rpx;
      display: flex;
      align-items: flex-end;
      font-size: 28rpx;
      color: #bebebe;
      line-height: 40rpx;
      text {
        font-size: 28rpx;
        margin-left: 8rpx;
      }
    }
    .active {
      font-size: 36rpx;
      color: #1e1e1e;
      font-weight: 600;
      position: relative;
      text {
        font-size: 28rpx;
      }
      &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 50rpx;
        width: 56rpx;
        height: 8rpx;
        background: linear-gradient(90deg, rgba(66, 110, 254, 0.5) 0%, #426efe 100%);
      }
    }
  }
}
.pjBox {
  margin-top: 32rpx;
  .pjName {
    display: flex;
    .left {
      width: 64rpx;
      height: 64rpx;
      margin-right: 16rpx;
    }
    .right {
      width: calc(100% - 80rpx);
      font-size: 26rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 36rpx;
      .name {
        margin-bottom: 8rpx;
        font-weight: 600;
      }
    }
  }
  .pjInfo {
    margin-left: 80rpx;
    background: #f5f7f9;
    border-radius: 16rpx;
    padding: 28rpx 24rpx;
    margin-top: 16rpx;
    .info {
      display: flex;
      align-items: center;
      font-size: 26rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #1e1e1e;
      line-height: 42rpx;
      margin-bottom: 10rpx;
      text {
        color: #1676fd;
      }
    }
  }
  .bottomPl {
    margin-left: 80rpx;
    margin-top: 20rpx;
    font-size: 24rpx;
    color: #bebebe;
    line-height: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.plInputBox {
  padding: 10rpx 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .btnBox {
    width: 16%;
    margin-left: 10rpx;
  }
}
.lookmore {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #1676fd;
  line-height: 36rpx;
  margin-top: 6rpx;
}
.buttomBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .iconBox {
    display: flex;
    align-items: center;
    margin-left: 20rpx;

    .itemBox {
      font-size: 24rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #666669;
      margin-right: 60rpx;
      text-align: center;
      .icon {
        width: 48rpx;
        height: 48rpx;
        &:active {
          width: 20rpx;
        }
      }
    }
  }

  .btn {
    width: 336rpx;
    height: 80rpx;
    background: #1676fd;
    border-radius: 40rpx;
    text-align: center;
    line-height: 80rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #ffffff;
  }
}
.imgBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 38rpx;
  image {
    width: 208rpx;
    height: 208rpx;
    border-radius: 16rpx;
    margin-right: 6rpx;
    margin-bottom: 6rpx;
  }
}
</style>
